/************************************************************
  *  * EaseMob CONFIDENTIAL 
  * __________________ 
  * changed by Wzz 2016.11.3
  *  
  * NOTICE: All information contained herein is, and remains 
  * the property of EaseMob Technologies.
  * Dissemination of this information or reproduction of this material 
  * is strictly forbidden unless prior written permission is obtained
  * from EaseMob Technologies.
  */
#import "ContactSelectionViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "EMSearchBar.h"
#import "EMRemarkImageView.h"
#import "BaseTableViewCell.h"
#import "RealtimeSearchUtil.h"
#import "HXRuntimeStatus.h"
#import "HXDDUserEntity.h"
#import "RomensSDK/UIViewController+HUD.h"
@interface ContactSelectionViewController ()<UISearchBarDelegate, UISearchDisplayDelegate>

@property (strong, nonatomic) NSMutableArray *contactsSource;
@property (strong, nonatomic) NSMutableArray *selectedContacts;
@property (strong, nonatomic) NSMutableArray *blockSelectedUsernames;

@property (strong, nonatomic) UIView *footerView;
@property (strong, nonatomic) UIScrollView *footerScrollView;
@property (strong, nonatomic) UIButton *doneButton;

@property (nonatomic) BOOL presetDataSource;

@end

@implementation ContactSelectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _contactsSource = [NSMutableArray array];
        _selectedContacts = [NSMutableArray array];
        
        [self setObjectComparisonStringBlock:^NSString *(id object) {
            HXDDUserEntity *buddy = (HXDDUserEntity *)object;
            return buddy.nick;
        }];
        [self setComparisonObjectSelector:^NSComparisonResult(id object1, id object2) {
            HXDDUserEntity *buddy1 = (HXDDUserEntity *)object1;
            HXDDUserEntity *buddy2 = (HXDDUserEntity *)object2;
            return [buddy1.nick caseInsensitiveCompare: buddy2.nick];

        }];
    }
    return self;
}

- (instancetype)initWithBlockSelectedUsernames:(NSArray *)blockUsernames
{
    self = [self initWithNibName:nil bundle:nil];
    if (self) {
        _blockSelectedUsernames = [NSMutableArray array];
        [_blockSelectedUsernames addObjectsFromArray:blockUsernames];
    }
    
    return self;
}

- (instancetype)initWithContacts:(NSArray *)contacts
{
    self = [self initWithNibName:nil bundle:nil];
    if (self) {
        _presetDataSource = YES;
        [_contactsSource addObjectsFromArray:contacts];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = NSLocalizedString(@"title.chooseContact", @"select the contact");
    self.navigationItem.rightBarButtonItem = nil;
//    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
//    backButton.accessibilityIdentifier = @"back";
//    [backButton setImage:[UIImage imageNamed:@"HuanXin.bundle/back.png"] forState:UIControlStateNormal];
//    [backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    [self.navigationItem setLeftBarButtonItem:backItem];
    
    [self.view addSubview:self.footerView];
    self.tableView.editing = YES;
    
    if ([_blockSelectedUsernames count] > 0) {
        for (NSString *username in _blockSelectedUsernames) {
            NSString*nick=[[HXRuntimeStatus instance] GetUserForName:username].nick;
            NSInteger section = [self sectionForString:nick];
            NSMutableArray *tmpArray = [_dataSource objectAtIndex:section];
            if (tmpArray && [tmpArray count] > 0) {
                for (int i = 0; i < [tmpArray count]; i++) {
                    HXDDUserEntity *buddy = [tmpArray objectAtIndex:i];
                    if ([buddy.name isEqualToString:username]) {
                        [self.selectedContacts addObject:buddy];
                        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
                        
                        break;
                    }
                }
            }
        }
        if ([_selectedContacts count] > 0) {
            [self reloadFooterView];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - getter

//- (UISearchBar *)searchBar
//{
//    if (_searchBar == nil) {
//        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
//        _searchBar.delegate = self;
//        _searchBar.placeholder = NSLocalizedString(@"search", @"Search");
//        _searchBar.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin;
//        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
//    }
//    
//    return _searchBar;
//}
//
//- (EMSearchDisplayController *)searchController
//{
//    if (_searchController == nil) {
//        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
//        _searchController.editingStyle = UITableViewCellEditingStyleInsert | UITableViewCellEditingStyleDelete;
//        _searchController.delegate = self;
//        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        
//        __weak ContactSelectionViewController *weakSelf = self;
//        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
//            static NSString *CellIdentifier = @"ContactListCell";
//            BaseTableViewCell *cell = (BaseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//            
//            // Configure the cell...
//            if (cell == nil) {
//                cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//            }
//            
//            HXDDUserEntity *buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
//            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:buddy.avatar] placeholderImage:[UIImage imageNamed:@"HuanXin.bundle/chatListCellHead"]];
//            cell.textLabel.text = buddy.nick;
//            
//            return cell;
//        }];
//        
//        [_searchController setCanEditRowAtIndexPath:^BOOL(UITableView *tableView, NSIndexPath *indexPath) {
//            if ([weakSelf.blockSelectedUsernames count] > 0) {
//                HXDDUserEntity *buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
//                return ![weakSelf isBlockUsername:buddy.nick];
//            }
//            
//            return YES;
//        }];
//        
//        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
//            return 50;
//        }];
//        
//        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
//            HXDDUserEntity *buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
//            if (![weakSelf.selectedContacts containsObject:buddy])
//            {
//                NSInteger section = [weakSelf sectionForString:buddy.nick];
//                if (section >= 0) {
//                    NSMutableArray *tmpArray = [weakSelf.dataSource objectAtIndex:section];
//                    NSInteger row = [tmpArray indexOfObject:buddy];
//                    [weakSelf.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO scrollPosition:UITableViewScrollPositionNone];
//                }
//                
//                [weakSelf.selectedContacts addObject:buddy];
//                [weakSelf reloadFooterView];
//            }
//        }];
//        
//        [_searchController setDidDeselectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
//            [tableView deselectRowAtIndexPath:indexPath animated:YES];
//            
//            HXDDUserEntity *buddy = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
//            if ([weakSelf.selectedContacts containsObject:buddy]) {
//                NSInteger section = [weakSelf sectionForString:buddy.nick];
//                if (section >= 0) {
//                    NSMutableArray *tmpArray = [weakSelf.dataSource objectAtIndex:section];
//                    NSInteger row = [tmpArray indexOfObject:buddy];
//                    [weakSelf.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section] animated:NO];
//                }
//                
//                [weakSelf.selectedContacts removeObject:buddy];
//                [weakSelf reloadFooterView];
//            }
//        }];
//    }
//    
//    return _searchController;
//}
//选择结果
- (UIView *)footerView
{
    if (_footerView == nil) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
        _footerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _footerView.backgroundColor = [UIColor colorWithRed:207 / 255.0 green:210 /255.0 blue:213 / 255.0 alpha:0.7];
        
        _footerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 0, _footerView.frame.size.width - 30 - 70, _footerView.frame.size.height - 5)];
        _footerScrollView.backgroundColor = [UIColor clearColor];
        [_footerView addSubview:_footerScrollView];
        
        _doneButton = [[UIButton alloc] initWithFrame:CGRectMake(_footerView.frame.size.width - 80, 8, 70, _footerView.frame.size.height - 16)];
        _doneButton.layer.cornerRadius = 5;//设置圆角
        [_doneButton setBackgroundColor:HXSystemColor];
        [_doneButton setTitle:NSLocalizedString(@"accept", @"Accept") forState:UIControlStateNormal];
        [_doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _doneButton.titleLabel.font = systemFont(14.0);
        [_doneButton setTitle:NSLocalizedString(@"ok", @"OK") forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:_doneButton];
    }
    
    return _footerView;
}

#pragma mark - Table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ContactListCell";
    BaseTableViewCell *cell = (BaseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    HXDDUserEntity *buddy = [[_dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:buddy.avatar] placeholderImage:[UIImage imageNamed:@"HuanXin.bundle/chatListCellHead"]];
    cell.textLabel.text = buddy.nick;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    if ([_blockSelectedUsernames count] > 0) {
        HXDDUserEntity *buddy = [[_dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        return ![self isBlockUsername:buddy.nick];
    }
    
    return YES;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [[_dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if (![self.selectedContacts containsObject:object])
    {
        [self.selectedContacts addObject:object];
        
        [self reloadFooterView];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HXDDUserEntity *buddy = [[_dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if ([self.selectedContacts containsObject:buddy]) {
        [self.selectedContacts removeObject:buddy];
        
        [self reloadFooterView];
    }
}

#pragma mark - UISearchBarDelegate

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
//{
//    [searchBar setShowsCancelButton:YES animated:YES];
//    [self.searchBar setCancelButtonTitle:NSLocalizedString(@"ok", @"OK")];
//    
//    return YES;
//}
//
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//{
//    __weak typeof(self) weakSelf = self;
//    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.contactsSource searchText:searchText collationStringSelector:@selector(nick) resultBlock:^(NSArray *results) {
//        if (results) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf.searchController.resultsSource removeAllObjects];
//                [weakSelf.searchController.resultsSource addObjectsFromArray:results];
//                [weakSelf.searchController.searchResultsTableView reloadData];
//                [self resultShow];//重设显示结果起点
//                
//                for (DDUserEntity *buddy in results) {
//                    if ([weakSelf.selectedContacts containsObject:buddy])
//                    {
//                        NSInteger row = [results indexOfObject:buddy];
//                        [weakSelf.searchController.searchResultsTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
//                    }
//                }
//            });
//        }
//    }];
//}
//
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
//{
//    return YES;
//}
//
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
//{
//    [searchBar resignFirstResponder];
//}
//
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
//{
//    searchBar.text = @"";
//    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
//    [searchBar resignFirstResponder];
//    [searchBar setShowsCancelButton:NO animated:YES];
//}
//
#pragma mark - UISearchDisplayDelegate

//- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
//{
//    tableView.editing = YES;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
//}
//#pragma mark -- 解决因为键盘的frame导致的UITableView的frame发生变化
//- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView {
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
//    
//}


////设置搜索结果底部
//- (void)keyboardWillHide {
//    
//    UITableView *resultTableView = [[self searchDisplayController] searchResultsTableView];
//    UIEdgeInsets inset;
//    CGFloat height = 216.0 + 20.0;
//    //有toolbar 在显示 没有隐藏
//    [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? (inset = UIEdgeInsetsMake(0, 0, height, 0)) : (inset = UIEdgeInsetsZero);
//    [resultTableView setShowsVerticalScrollIndicator:YES];
//    [resultTableView setContentInset:inset];//视图在scrollView中的位置
//    [resultTableView setScrollIndicatorInsets:inset];//指定滚动条在scrollerView中的位置
//}
//搜索结果显示后，重新设置结果视图的tableview的起点
//- (void)resultShow {
//    UITableView *resultTableView = [[self searchDisplayController] searchResultsTableView];
//    [resultTableView setShowsVerticalScrollIndicator:YES];
//    [resultTableView setContentOffset:CGPointMake(0, 0)];
//}
#pragma mark - private

- (BOOL)isBlockUsername:(NSString *)username
{
    if (username && [username length] > 0) {
        if ([_blockSelectedUsernames count] > 0) {
            for (NSString *tmpName in _blockSelectedUsernames) {
                if ([username isEqualToString:tmpName]) {
                    return YES;
                }
            }
        }
    }
    
    return NO;
}

- (void)reloadFooterView
{
    [self.footerScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat imageSize = self.footerScrollView.frame.size.height;
    NSInteger count = [self.selectedContacts count];
    self.footerScrollView.contentSize = CGSizeMake(imageSize * count, imageSize);
    for (int i = 0; i < count; i++) {
        HXDDUserEntity *buddy = [self.selectedContacts objectAtIndex:i];
        EMRemarkImageView *remarkView = [[EMRemarkImageView alloc] initWithFrame:CGRectMake(i * imageSize, 0, imageSize, imageSize)];
        [remarkView setWebImageUrl:[NSURL URLWithString:buddy.avatar] image:[UIImage imageNamed:@"HuanXin.bundle/chatListCellHead"]];
        remarkView.remark = buddy.nick;
        [self.footerScrollView addSubview:remarkView];
    }
    
    if ([self.selectedContacts count] == 0) {
        [_doneButton setTitle:NSLocalizedString(@"ok", @"OK") forState:UIControlStateNormal];
    }
    else{
        [_doneButton setTitle:[NSString stringWithFormat:NSLocalizedString(@"doneWithCount", @"Done(%i)"), [self.selectedContacts count]] forState:UIControlStateNormal];
    }
}

#pragma mark - public

- (void)loadDataSource
{
    [self showHudInView:self.view hint:NSLocalizedString(@"loadData", @"Load data...")];
    [_dataSource removeAllObjects];
    [_contactsSource removeAllObjects];
    
    for (HXDDUserEntity* user in [HXRuntimeStatus instance].ALLUsers) {
        [_contactsSource addObject:user];
    }
    [_dataSource addObjectsFromArray:[self sortRecords:[HXRuntimeStatus instance].ALLUsers]];
    [self hideHud];
    [self.tableView reloadData];
}

- (void)doneAction:(id)sender
{
    if(self._ContactSelectionBlock)
    {
       self._ContactSelectionBlock(self.selectedContacts);
      [self.navigationController popViewControllerAnimated:NO];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(viewController:didFinishSelectedSources:)]) {
        if ([_blockSelectedUsernames count] == 0) {
            [_delegate viewController:self didFinishSelectedSources:self.selectedContacts];
            [self.navigationController popViewControllerAnimated:NO];
        }
        else{
            NSMutableArray *resultArray = [NSMutableArray array];
            for (HXDDUserEntity *buddy in self.selectedContacts) {
                if(![self isBlockUsername:buddy.nick])
                {
                    [resultArray addObject:buddy];
                }
            }
            [_delegate viewController:self didFinishSelectedSources:resultArray];
            [self.navigationController popViewControllerAnimated:NO];
        }
    }
}

@end
